<template>
  <div>
    <div>分配权限功能</div>
    <el-tree ref="tree" node-key="id" show-checkbox default-expand-all check-strictly :data="treeData" :props="defaultProps" />

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { getRoleDetail, assignPerm } from '@/api/setting'
import { transTree } from '@/utils'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    // console.log(this.roleId)
    this.getPermissionList()
    this.getRoleDetail()
  },
  methods: {
    // 通过id获取角色信息
    async getRoleDetail() {
      const res = await getRoleDetail(this.roleId)
      // console.log(res)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },

    // 获取权限点列表
    async getPermissionList() {
      const res = await getPermissionList()
      // console.log(res)
      this.treeData = transTree(res.data, '0')
    },

    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 设置权限按钮
    async setRolesBtn() {
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({ id: this.roleId, permIds })
      // console.log(res)
      // 提示
      this.$message.success(res.message)
      // 关闭弹框
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
